package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.text.TextPaint;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.CommentReply;
import com.sywb.chuangyebao.bean.NewsOwner;
import com.sywb.chuangyebao.bean.QARichInfo;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.TimeUtils;

import java.util.ArrayList;
import java.util.List;

public interface CommentReplyContract {

    interface BaseView extends BaseRecyclerContract.View {

        CommentReply getComment();

        void setCommentCount(int commentCount);

        void setCommentThumb(boolean isThumb, int thumbCount);

        void setReplyName(String replyType, int replyId, int toUid, String name);
    }

    class Presenter<T extends BaseView> extends BaseRecyclerContract.Presenter<T> {

        protected ReplyAdapter recyclerAdapter;

        protected CommentReply commentInfo;
        protected int pageNumber = 1;

        @Override
        public void onStart() {
            super.onStart();

            commentInfo = mView.getComment();
            commentInfo.reply_id = -1;
            commentInfo.reply_obj = null;

            mView.setCommentCount(commentInfo.reply_count);

            recyclerAdapter = new ReplyAdapter(mActivity, commentInfo);
            recyclerAdapter.setHeaderView(R.layout.item_answer_reply);
            recyclerAdapter.setEmptyView(R.layout.layout_news_no_comment, true);

            setRecyclerAdapter(recyclerAdapter);

            initData();
        }

        @Override
        public void initData() {
            onStartAsync();
            getCommentReplyList();
        }

        @Override
        public void onStartRefresh() {
            pageNumber = 1;
            getCommentReplyList();
        }

        @Override
        public void onStartLoadMore() {
            pageNumber++;
            getCommentReplyList();
        }

        private void getCommentReplyList() {
            HttpUtils.listCommentReply(commentInfo.comment_id, pageNumber, new HttpCallback<List<CommentReply>>() {
                @Override
                public void onSuccess(List<CommentReply> commentReplies) {
                    if (pageNumber == 1) {
                        recyclerAdapter.clearDatas();
                        // recyclerAdapter.addData(0, commentInfo);
                    }
                    recyclerAdapter.notifyDataChangedAfterLoadMore(commentReplies);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                    isNoData();
                }
            });
        }

        /**
         * 点赞/取消点赞
         */
        public void agree(String topicType, int parentId, boolean isAgree, int postion) {
            if (!Utils.checkIsLogin()) {
                return;
            }
            HttpUtils.agree(topicType, parentId, isAgree, new HttpCallback<Object>(postion) {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object o) {
                    int postion = (int) data;
                    if (postion == 0) {
                        commentInfo.is_thumb = !commentInfo.is_thumb;
                        commentInfo.thumb_count = commentInfo.is_thumb ? commentInfo.thumb_count + 1 : commentInfo.thumb_count - 1;
                        mView.setCommentThumb(commentInfo.is_thumb, commentInfo.thumb_count);
                    } else {
                        CommentReply comment = recyclerAdapter.getItem(postion - 1);
                        comment.is_thumb = !comment.is_thumb;
                        comment.thumb_count = comment.is_thumb ? comment.thumb_count + 1 : comment.thumb_count - 1;
                    }
                    recyclerAdapter.notifyDataSetChanged();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        /**
         * 添加评论回复
         *
         * @param replyType 回复目标类型 'comment'或 'reply'
         * @param replyId   回复目标ID，当类型为comment时，该值为回复的评论ID
         * @param content   回复内容
         */
        public void addCommentReply(String replyType, int replyId, int toUid, String content) {
            if (!Utils.checkIsNext(mView.getMyFragmentManager())) {
                return;
            }
            HttpUtils.addCommentReply(replyType, replyId, commentInfo.comment_id, toUid, content, new HttpCallback<Object>() {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object data) {
                    commentInfo.reply_count = commentInfo.reply_count + 1;
                    mView.setCommentCount(commentInfo.reply_count);
                    onStartRefresh();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        /**
         * 删除评论回复
         *
         * @param replyId 评论回复ID
         */
        public void delCommentReply(int replyId) {
            if (!Utils.checkIsLogin()) {
                return;
            }
            HttpUtils.delCommentReply(replyId, new HttpCallback<Object>() {
                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object data) {
                    commentInfo.reply_count = commentInfo.reply_count - 1;
                    mView.setCommentCount(commentInfo.reply_count);
                    onStartRefresh();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        @Override
        public void onRecyclerItemClick(int postion) {
            super.onRecyclerItemClick(postion);
        }

        @Override
        public void onRecyclerItemLongClick(View view, int postion) {
            if (postion > 0) {
                CommentReply comment = recyclerAdapter.getItem(postion - 1);
                if (String.valueOf(comment.from_uid).equals(SharedUtils.getString(Constants.USEROPENID))) {
                    delCommentReply(comment.reply_id);
                }
            }
        }

        @Override
        public void onRecyclerItemChildClick(View view, int postion) {
            CommentReply comment;
            if (postion == 0) {
                comment = commentInfo;
            } else {
                comment = recyclerAdapter.getItem(postion - 1);
            }
            switch (view.getId()) {
                case R.id.iv_head:
                case R.id.iv_user_type:
                case R.id.tv_name:
//                    mView.advance(UserIndexActivity.class, comment.from_uid);
                    Utils.goUserIndex(mView, comment.from_uid);
                    break;
                case R.id.tv_reply:
                    mView.setReplyName("reply", comment.reply_id, comment.from_uid, "回复 " + comment.from_user.getShowName());
                    break;
                case R.id.tv_zan_count:
                case R.id.iv_zan:
                    if (postion == 0) {
                        agree("comment", comment.comment_id, !comment.is_thumb, postion);
                    } else {
                        agree("reply", comment.reply_id, !comment.is_thumb, postion);
                    }
                    break;
            }
        }

        @Override
        public boolean useRecyclerDivider() {
            return false;
        }
    }

    class ReplyAdapter extends BaseRecyclerAdapter<CommentReply> {

        private Activity mActivity;
        private CommentReply commentInfo;

        public ReplyAdapter(Activity activity, CommentReply commentInfo) {
            super(activity, R.layout.item_answer_reply);
            this.mActivity = activity;
            this.commentInfo = commentInfo;
        }

        @Override
        protected void setItemData(ViewHolderHelper viewHolderHelper, final int i, CommentReply model) {
            if (model == null) {
                return;
            }

            viewHolderHelper.setItemChildClickListener(R.id.iv_head);
            viewHolderHelper.setItemChildClickListener(R.id.iv_user_type);
            viewHolderHelper.setItemChildClickListener(R.id.tv_name);
            viewHolderHelper.setItemChildClickListener(R.id.iv_zan);
            viewHolderHelper.setItemChildClickListener(R.id.tv_zan_count);
            viewHolderHelper.setItemChildClickListener(R.id.tv_reply);

            NewsOwner commentUser = model.from_user;
            if (commentUser != null) {
                ImageView imageView = viewHolderHelper.getView(R.id.iv_head);
                GlideUtils.getCircleImageToUrl(mActivity, commentUser.getShowAvatar(), imageView);

                int userRole = commentUser.getUserRole();
                if (userRole == Constants.USER_TYPE_NORMAL) {
                    viewHolderHelper.setVisibility(R.id.iv_user_type, android.view.View.GONE);
                } else {
                    viewHolderHelper.setVisibility(R.id.iv_user_type, android.view.View.VISIBLE);
                    switch (userRole) {
                        case Constants.USER_TYPE_V:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.official_icon);
                            break;
                        case Constants.USER_TYPE_PROJECT:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_project);
                            break;
                        case Constants.USER_TYPE_SERVICE:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_service);
                            break;
                        case Constants.USER_TYPE_TUTOR:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_teacher);
                            break;
                    }
                }

                viewHolderHelper.setText(R.id.tv_name, commentUser.getShowName());
            }

            RichTextView tvComment = viewHolderHelper.getView(R.id.tv_comment);
            tvComment.setExpandView(false);

            if (model.reply_obj != null) {
                //  String division = " //";
                List<QARichInfo> richInfoList = new ArrayList<>();
                QARichInfo qaRichInfo = new QARichInfo();
                qaRichInfo.position = model.content.length();
                qaRichInfo.uid = model.reply_obj.to_user.uid;
                qaRichInfo.richName = "@" + model.reply_obj.to_user.getShowName() + " ";
                richInfoList.add(qaRichInfo);
                String data = model.content + qaRichInfo.richName + model.reply_obj.content;
                tvComment.setRichText(data, richInfoList);

                tvComment.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
                    @Override
                    public void onAtClick(RichTextView richTextView, Object userId) {
                        Utils.goUserIndex(mActivity, (Integer) userId);
                    }

                    @Override
                    public void onTopicClick(RichTextView richTextView, Object topicId) {

                    }

                    @Override
                    public void onEmojiClick(RichTextView richTextView, Object emoji) {

                    }

                    @Override
                    public void onUrlClick(RichTextView richTextView, Object url) {

                    }

                    @Override
                    public void onAllClick(RichTextView richTextView) {

                    }
                });
            } else {
                tvComment.setRichText(model.content, null);
            }

            tvComment.setTextColor(ContextCompat.getColor(mActivity, R.color.colorDark));

            viewHolderHelper.setVisibility(true, R.id.tv_point, R.id.tv_reply);
            TextView tvReply = viewHolderHelper.getView(R.id.tv_reply);
            int verticalPadding = (int) mContext.getResources().getDimension(R.dimen.dp_4);
            tvReply.setText("回复");
            tvReply.setPadding(0, verticalPadding, 0, verticalPadding);
            tvReply.setBackgroundColor(Color.TRANSPARENT);
            tvReply.setVisibility(View.VISIBLE);

            viewHolderHelper.setText(R.id.tv_time, TimeUtils.transformDate10(model.date_time));

            //是否赞
            viewHolderHelper.setImageResource(R.id.iv_zan, model.is_thumb ? R.drawable.praise_red : R.drawable.praise);
            viewHolderHelper.setTextColorRes(R.id.tv_zan_count, model.is_thumb ? R.color.messageRed : R.color.colorGray);
            viewHolderHelper.setText(R.id.tv_zan_count, model.getThumbCount());
        }

        @Override
        protected void setHeaderData(ViewHolderHelper viewHolderHelper, int position) {

            viewHolderHelper.setItemChildClickListener(R.id.iv_head);
            viewHolderHelper.setItemChildClickListener(R.id.iv_user_type);
            viewHolderHelper.setItemChildClickListener(R.id.tv_name);
            viewHolderHelper.setItemChildClickListener(R.id.iv_zan);
            viewHolderHelper.setItemChildClickListener(R.id.tv_zan_count);
            viewHolderHelper.setItemChildClickListener(R.id.tv_reply);

            NewsOwner commentUser = commentInfo.from_user;
            if (commentUser != null) {
                ImageView imageView = viewHolderHelper.getView(R.id.iv_head);
                GlideUtils.getCircleImageToUrl(mActivity, commentUser.getShowAvatar(), imageView);

                int userRole = commentUser.getUserRole();
                if (userRole == Constants.USER_TYPE_NORMAL) {
                    viewHolderHelper.setVisibility(R.id.iv_user_type, android.view.View.GONE);
                } else {
                    viewHolderHelper.setVisibility(R.id.iv_user_type, android.view.View.VISIBLE);
                    switch (userRole) {
                        case Constants.USER_TYPE_V:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.official_icon);
                            break;
                        case Constants.USER_TYPE_PROJECT:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_project);
                            break;
                        case Constants.USER_TYPE_SERVICE:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_service);
                            break;
                        case Constants.USER_TYPE_TUTOR:
                            viewHolderHelper.setImageResource(R.id.iv_user_type, R.drawable.icon_teacher);
                            break;
                    }
                }

                viewHolderHelper.setText(R.id.tv_name, commentUser.getShowName());
            }

            RichTextView tvComment = viewHolderHelper.getView(R.id.tv_comment);
            tvComment.setExpandView(false);
            tvComment.setRichText(commentInfo.content, null);

            TextPaint textPaint = tvComment.getPaint();
            textPaint.setFakeBoldText(true);
            tvComment.setTextSize(16);
            tvComment.setTextColor(ContextCompat.getColor(mActivity, R.color.colorBlack));

            viewHolderHelper.setVisibility(false, R.id.tv_point, R.id.tv_reply);

            viewHolderHelper.setText(R.id.tv_time, TimeUtils.transformDate10(commentInfo.date_time));

            //是否赞
            viewHolderHelper.setImageResource(R.id.iv_zan, commentInfo.is_thumb ? R.drawable.praise_red : R.drawable.praise);
            viewHolderHelper.setTextColorRes(R.id.tv_zan_count, commentInfo.is_thumb ? R.color.messageRed : R.color.colorGray);
            viewHolderHelper.setText(R.id.tv_zan_count, commentInfo.getThumbCount());
        }

        @Override
        protected void setEmptyData(ViewHolderHelper viewHolderHelper, int position) {
            viewHolderHelper.setText(R.id.tv_content, "暂无回复,点击抢沙发");
        }
    }

}

